<?php

$host = "localhost";
$user = "root";
$pass = "";
$dbnames = array("yap_db","yyp2");


$UserAgent = $_SERVER['HTTP_USER_AGENT'];
$console = strlen($UserAgent)>0?false:true;

if ($console){
	define("NL","\n");
	define("SPACE"," ");
	define("TAB","\t");
}else{
	define("NL","<br />");
	define("SPACE","&nbsp;");
	define("TAB",SPACE.SPACE.SPACE.SPACE);
}

$conn = mysql_connect($host,$user,$pass); if (!$conn){die(mysql_error());}

$out = "MySQL optimize script".NL."------------------------------";

foreach ($dbnames as $dbname){
	$res = mysql_select_db($dbname,$conn);if(!$res){die(mysql_error());}
	
	$q = "SHOW TABLE STATUS";
	$res = mysql_query($q,$conn);
	
	$repaired=false;
	//@system("clear");
	
	$out .= NL."DB: $dbname";
	
	while (1) {
		$r = mysql_fetch_assoc($res);
		if(!$r){
			break;
		}
		$name = $r["Name"];
		$free = $r["Data_free"];
		
		if($free > 0){
			$repaired=true;
			$res1 = mysql_query("OPTIMIZE TABLE $name"); if (!$res1){die(mysql_error());}
			$out .= NL.TAB."$name - $free B repaired";
		}
	}
	
	if(!$repaired){
		$out .= NL.TAB."Nothing repaired.".NL.TAB."Everything seems to be fine";
	}	
}
echo $out;
$filename = "logs/optimize/log.log";
if (file_exists($filename)){
	$divide = "\r\n------------------------------------------\r\n";
	$contents = date("d.m.Y H:i:s")."\r\n".$out.$divide.file_get_contents($filename);
	file_put_contents($filename,$content);
}

?>